<template>
  <div class="page-content">
    <!-- 工具栏区域 -->
    <table-bar :showTop="false" :columns="columns" @changeColumn="changeColumn">
      <!-- 条件查询区域 -->
      <div slot="top">暂无查询方式</div>
      <!-- 左侧按钮 -->
      <div slot="bottom">
        <el-button type="primary" @click="addRoleDialogVisible = true" plain class="addRoleBtn">添加角色</el-button>
      </div>
    </table-bar>
    <el-table :data="rolesList" style="width: 100%">
      <el-table-column prop="name" label="角色标签" v-if="columns[0].show"></el-table-column>
      <el-table-column label="拥有权限" v-if="columns[1].show">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-search" @click="checkoutRights(scope.row.id)">查看权限</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-if="columns[2].show">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-s-tools" @click="allotRights(scope.row)">分配权限</el-button>
          <el-button type="text" icon="el-icon-edit" style="color: #FA6962" @click="deleteRole(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: center;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageInfo.currentPage" :page-sizes="[5, 10, 20, 30, 40, 50]" :page-size="pageInfo.pageSize" :total="pageInfo.total" layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="28%" @closed="reSetAddRole">
      <span>
        <el-form label-position="right" ref="addRoleRef" :rules="addRoleRules" :model="addRoleForm" label-width="80px">
          <el-form-item label="角色标签" prop="name">
            <el-input v-model="addRoleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="说明" prop="remarks">
            <el-input v-model="addRoleForm.remarks"></el-input>
          </el-form-item>
          <el-form-item label="权重">
            <el-input-number v-model="addRoleForm.weight" :min="1" :max="99" label="权重"></el-input-number>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看权限 -->
    <el-dialog title="角色权限" :visible.sync="roleRightsDialogVisible" width="60%">
      <el-row v-for="(item1, index1) in roleRightsData" :key="index1" :class="index1 === 0 ? ['vcenter', 'btTop', 'btBottom', 'padd'] : ['vcenter', 'btBottom', 'padd']">
        <!-- 渲染一级权限 -->
        <el-col :span="5">
          <el-tag>{{item1.title}}</el-tag>
          <i class="el-icon-caret-right"></i>
        </el-col>
        <!-- 渲染二、三权限 -->
        <el-col :span="19">
          <el-row v-for="(item2, index2) in item1.childPermission" :key="index2" :class="index1 === 0 ? ['vcenter', 'btTop', 'btBottom', 'padd'] : ['vcenter', 'btBottom', 'padd']">
            <!-- 渲染二级权限 -->
            <el-col :span="5" class="bdHeight vcenter">
              <el-tag type="success">{{item2.title}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染三权限 -->
            <el-col>
              <el-row v-for="(item3, index3) in item2.childPermission" :key="index3" class="vcenter">
                <!-- 渲染三级权限 -->
                <el-col class="bdHeight vcenter">
                  <el-tag type="warning">{{item3.title}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="roleRightsDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-drawer :withHeader="false" :show-close="false" :visible.sync="allotRightsDialogVisible" @close="resetRights">
      <span class="drawerBtn">
        <el-button size="medium" @click="allotRightsDialogVisible = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="allotNewRights">分配权限</el-button>
      </span>
      <el-tree ref="rightsTree" :data="rightsList" show-checkbox default-expand-all node-key="id" :default-checked-keys="defaultCheckedIds" :props="defaultProps" check-on-click-node></el-tree>
    </el-drawer>
  </div>
</template>

<script>
import {
  getAllRolesByPages,
  confirmAddRole,
  getAllRoles,
  checkoutRoleRights,
  allRights,
  deleteRole,
  editRole,
} from '@/api/Basic/AuthorityManagement'

export default {
  name: 'AuthorityManagement',
  meta: {
    title: '权限管理',
  },
  data() {
    return {
      columns: [
        { name: '角色标签', show: true },
        { name: '拥有权限', show: true },
        { name: '操作', show: true },
      ],
      msg: '权限管理',
      addRoleDialogVisible: false,
      roleRightsDialogVisible: false,
      allotRightsDialogVisible: false,
      rolesSearch: '',
      rolesList: [],
      rightsList: [],
      currentRightsIds: [],
      currentHalfRightsIds: [],
      currentId: '',
      currentRemarks: '',
      currentName: '',
      defaultProps: {
        children: 'childPermission',
        label: 'title',
      },
      defaultCheckedIds: [],
      pageInfo: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      addRoleForm: {
        name: '',
        remarks: '',
        weight: '',
      },
      addRoleRules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        remarks: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
      },
      roleRightsData: [],
    }
  },
  created() {
    this.getAllRoles()
    this.getPageRolesList()
  },
  methods: {
    // 获取所有角色列表
    async getAllRoles() {
      const { data: res } = await getAllRoles()
      if (res.statusCode !== 20000) {
        console.log(res,'角色表111')
        return this.$message.error(res.message)
      }
    },
    // columns改变
    changeColumn(columns) {
      this.columns = columns
      this.$refs.flowListRef.doLayout()
    },
    // 获取分页角色列表
    async getPageRolesList() {
      const { data: res } = await getAllRolesByPages(
        this.pageInfo.currentPage,
        this.pageInfo.pageSize
      )
      if (res.statusCode !== 20000) {
        console.log(res,'角色列表111')
        return this.$message.error(res.message)
      }
      this.rolesList = res.data.records
      this.pageInfo.total = res.data.total
    },
    // 页面列表数发生改变
    handleSizeChange(newSize) {
      this.pageInfo.pageSize = newSize
      this.getPageRolesList()
    },
    // 页码值发生改变
    handleCurrentChange(newPage) {
      this.pageInfo.currentPage = newPage
      this.getPageRolesList()
    },
    // 确认添加角色
    addRole() {
      this.$refs.addRoleRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await confirmAddRole(this.addRoleForm)
        if (res.statusCode !== 20000) {
          console.log(res)
          return this.$message.error(res.message)
        }
        this.addRoleDialogVisible = false
        this.$message.success(res.message)
        this.getAllRoles()
        this.getPageRolesList()
      })
    },
    // 关闭清空添加用户信息
    reSetAddRole() {
      this.addRoleForm.name = ''
      this.addRoleForm.remarks = ''
      this.addRoleForm.weight = 1
    },
    // 查看角色的权限
    async checkoutRights(id) {
      this.roleRightsDialogVisible = true
      const { data: res } = await checkoutRoleRights(id)
      if (res.statusCode !== 20000) {
        return this.$message.error(res.message)
      }
      this.roleRightsData = res.data
      console.log(res, '查看角色的权限')
    },
    // 点击分配权限按钮
    async allotRights(role) {
      this.allotRightsDialogVisible = true
      this.checkoutAllRights()
      const { data: res } = await checkoutRoleRights(role.id)
      if (res.statusCode !== 20000) {
        return this.$message.error(res.message)
      }
      this.roleRightsData = res.data
      this.defaultChecked(this.roleRightsData)
      console.log(this.defaultCheckedIds, 'defaultCheckedIds');
      this.currentId = role.id
      this.currentRemarks = role.remarks
      this.currentName = role.name
    },
    // 更新分配权限（修改角色）
    async allotNewRights() {
      this.currentRightsIds = this.$refs.rightsTree.getCheckedKeys()
      this.currentHalfRightsIds = this.$refs.rightsTree.getHalfCheckedKeys()
      this.currentRightsIds = [...this.currentRightsIds, ...this.currentHalfRightsIds]
      const { data: res } = await editRole(
        this.currentId,
        this.currentName,
        this.currentRightsIds,
        this.currentRemarks
      )
      if (res.statusCode !== 20000) {
        return this.$message.error(res.message)
      }
      this.$message.success(res.message)
      this.allotRightsDialogVisible = false
      this.getAllRoles()
      this.getPageRolesList()
      console.log('修改角色')
      console.log(res)
      console.log('修改角色')
    },
    // 查看所有权限
    async checkoutAllRights() {
      const { data: res } = await allRights()
      if (res.statusCode !== 20000) {
        return this.$message.error(res.message)
      }
      this.rightsList = res.data
      console.log(res,'所有权限');
    },
    // 默认展开
    defaultChecked(rightsData) {
      for (var i = 0; i < rightsData.length; i++) {
        if (rightsData[i].childPermission.length !== 0) {
          this.defaultChecked(rightsData[i].childPermission)
        } else {
          this.defaultCheckedIds.push(rightsData[i].id)
          continue
        }
      }
    },
    // 清空defaultCheckedIds[]
    async resetRights() {
      this.defaultCheckedIds = []
    },
    // 删除角色
    deleteRole(id) {
      this.$confirm('是否永久删除该角色（此操作不可撤销）？', '删除角色', {
        distinguishCancelAndClose: true,
        confirmButtonText: '删除',
        cancelButtonText: '取消',
      })
        .then(async () => {
          const { data: res } = await deleteRole(id)
          if (res.statusCode !== 20000) {
            console.log(res)
            return this.$message.error(res.message)
          }
          this.$message.warning(res.message)
          let total = this.pageInfo.total
          let size = this.pageInfo.pageSize
          this.getAllRoles()
          this.getPageRolesList()
          if (this.pageInfo.currentPage !== 1 && total % size === 1) {
            this.pageInfo.currentPage--
            this.getAllRoles()
            this.getPageRolesList()
          }
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.card {
  width: 100%;
}

/deep/ .el-table th {
  z-index: 99;
  text-align: center;
  background-color: rgb(248, 248, 248);
}

/deep/ .el-table td {
  z-index: 99;
  text-align: center;
}

.changeLevel {
  padding-left: 0;
  padding-right: 0;
  width: 40px;
}

.bdHeight {
  height: 40px;
}

.vcenter {
  display: flex;
  align-items: center;
}

.btTop {
  border-top: 1px dashed #ccc;
}
.btBottom {
  border-bottom: 1px dashed #ccc;
}

.padd {
  padding: 20px 0;
}

/deep/ .el-drawer__body {
  overflow: auto !important;
}

.drawerBtn {
  margin: 40px 20px;
  display: flex;
  justify-content: flex-end;
}

.addRoleBtn {
  display: flex;
  justify-content: flex-start;
}
</style>